import { defineStore } from 'pinia';
import helper from "@/sheep/helper"


const giftcart = defineStore({
  id: 'giftcart',
  state: () => ({
	cartList:[]
  }),

  actions: {
		addCart(cartInfo){
			let currentIndex = this.cartList.findIndex( i => i.form.goods_id == cartInfo.form.goods_id && i.form.specs_info.name == cartInfo.form.specs_info.name && i.form.specs_info.point == cartInfo.form.specs_info.point)
			if(currentIndex >= 0) {
				let currentCart = this.cartList[currentIndex].form
				if(currentCart.specs_info.name === cartInfo.form.specs_info.name && currentCart.specs_info.point == cartInfo.form.specs_info.point) {
					helper.toast('加入购物车成功！')
					return currentCart.number = currentCart.number + cartInfo.form.number			
				}
			}  
			helper.toast('加入购物车成功！')
			this.cartList = this.cartList.concat([cartInfo])
		},
		clearCart(){
			this.cartList = []
		},
		changeNumber(index,value){
			if(value == 0) {
				helper.showModal({content:`确认移除${this.cartList[index].info.name}房间吗？`}).then( () => {
					this.cartList.splice(index,1)
				}).catch( err => {})
			}else {
				this.cartList[index].form.number = value
			}
		}
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'giftcart-store',
      },
    ],
  },
});

export default giftcart;
